import json
from django_ratelimit.decorators import ratelimit
from django.core.mail import send_mail
from django.conf import settings
from django.http import  JsonResponse
from myApp.utils.result import R
from django.views.decorators.http import require_POST, require_GET
from myApp.utils.enums import StatusCodeEnum
import requests

import logging

logger = logging.getLogger('mylogger')



@require_POST
def email(request):
    # print(request)
    data = json.loads(request.body)
    code = data['code']
    msg = data['msg']

    subject = "报错"  # 标题
    message = str(code) + "--" + msg  # 内容
    to_email = '2779202813@qq.com'  # 收件人

    # settings.EMAIL_FROM 是发件人抬头, 收件人必须是列表,可多个收件人
    a = send_mail(subject, message, settings.EMAIL_FROM, [to_email])  # 更多参数请查看源码
    # print(a)
    # print("发送成功")
    context = R.ok().data()
    context['data'] = '好的我知道啦'
    return JsonResponse(context)


@require_GET
def index(request):
    context = R.ok().data()
    context['data'] = 'hello'
    return JsonResponse(context)


class OpenId:
    def __init__(self, jscode):
        self.url = 'https://api.weixin.qq.com/sns/jscode2session'
        self.app_id = 'wx43ffd65e09fed91a'
        self.app_secret = '943a38e415b7e1ff61d87980410b340b'
        self.jscode = jscode

    def get_openid(self):
        url = self.url + "?appid=" + self.app_id + "&secret=" + self.app_secret + "&js_code=" + self.jscode + "&grant_type=authorization_code"
        res = requests.get(url)
        try:
            openid = res.json()['openid']
            session_key = res.json()['session_key']
        except Exception as e:
            logging.error(e)
            return e
        else:
            return openid, session_key

@require_POST
@ratelimit(key='ip', rate='1/3s', block=True)
def login(request):
    data = json.loads(request.body)
    login_code = data['code']

    try:
        data = OpenId(login_code).get_openid()
        openid = data[0]
        session_key = data[1]

        context = R.ok().data()
        context['data'] = data
        return JsonResponse(context)
    except Exception as e:
        context = R.set_result(StatusCodeEnum.ERR_LOGIN).data()
        return JsonResponse(context)


